import React, { Component } from 'react';
import { Button, Icon, Input, Table, message, Popconfirm, Empty, Tooltip, Modal } from 'antd';
import _ from 'lodash';
import WhiteListModal from './components/white-list-modal';
import EmptyDataImg from '@images/empty-data-blue.png';
import {
  getWhiteList,
  addWhiteIp,
  deleteWhiteIp,
  modWhiteIp,
  dropWhiteIp,
  batchDelWhiteIp
} from '@api/task';
import './index.less';

const Search = Input.Search;
const prefixCls = 'white-list';
const OP_TYPE = {
  del: '批量删除白名单',
  drop: '清空禁扫目标'
};

class WhiteList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      filter: {},
      total: 0,
      count: 0,
      loading: false,
      modalVisible: false,
      confirmLoading: false,
      rowData: {},
      selectedRows: [],
      selectedRowKeys: [],
      modalType: ''
    };
  }

  componentDidMount() {
    this.getWhiteList();
  }

  getWhiteList = () => {
    const filter = _.clone(this.state.filter);
    if (filter.search) {
      filter.search = filter.search.replace(/\\/g, '\\\\');
      filter.search = filter.search.replace(/\|/g, '\\|');
    }
    this.setState({ loading: true });
    getWhiteList(filter)
      .then(res => {
        const count = _.get(res, 'data.data.count', 0);
        const total = _.get(res, 'data.data.total', 0);
        const data = _.get(res, 'data.data.list', []);
        this.setState({ count, total, data, loading: false });
      })
      .catch(() => {
        message.error('获取列表失败');
        this.setState({ loading: false });
      });
  };

  onClickSubmit = (type, body) => {
    this.setState({ confirmLoading: true });
    if (type === 'add') {
      addWhiteIp(body)
        .then(() => {
          message.success('添加成功');
          this.setState({ confirmLoading: false }, () => {
            this.wrapChangeModalVisible(false);
            this.getWhiteList();
          });
        })
        .catch(({ message: msg }) => {
          message.error(msg || '添加失败');
          this.setState({ confirmLoading: false });
          this.wrapChangeModalVisible(false);
        });
    } else if (type === 'edit') {
      modWhiteIp(body)
        .then(() => {
          message.success('编辑成功');
          this.setState({ confirmLoading: false }, () => {
            this.wrapChangeModalVisible(false);
            this.getWhiteList();
          });
        })
        .catch(({ message: msg }) => {
          message.error(msg || '编辑失败');
          this.setState({ confirmLoading: false });
        });
    }
  };

  deleteWhiteIp = id => {
    // eslint-disable-next-line
    deleteWhiteIp({ ip_id: id })
      .then(() => {
        message.success('删除成功');
        this.getWhiteList();
      })
      .catch(() => {
        message.error('删除失败');
      });
  };

  onSearchChange = e => {
    let { filter } = this.state;
    filter.search = e.target.value;
    this.setState({ filter });
  };

  wrapChangeModalVisible = (visible, rowData = {}) => {
    this.setState({
      modalVisible: visible,
      rowData
    });
  };

  onTableChange = pagination => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    const { filter } = this.state;
    const { current, pageSize } = pagination;

    filter.page = current;
    filter.pageSize = pageSize;

    this.setState({ filter }, this.getWhiteList);
  };

  batchDel = type => {
    this.setState({ modalType: type });
  };

  onDelOrDrop = () => {
    const { selectedRows, modalType } = this.state;
    const request = modalType === 'drop' ? dropWhiteIp : batchDelWhiteIp;
    const tipInfo = modalType === 'drop' ? '清空白名单' : '批量删除白名单';
    request({ ipIds: selectedRows })
      .then(() => {
        this.setState({ modalType: '', selectedRows: [], selectedRowKeys: [] });
        message.success(`${tipInfo}成功`);
        this.getWhiteList();
      })
      .catch(() => {
        message.success(`${tipInfo}失败`);
      });
  };

  render() {
    const {
      filter,
      loading,
      count,
      total,
      data,
      modalVisible,
      confirmLoading,
      rowData,
      selectedRows,
      selectedRowKeys,
      modalType
    } = this.state;
    const columns = [
      {
        title: 'IP',
        dataIndex: 'ip',
        width: '25%'
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        width: '55%'
      },
      {
        title: '操作',
        render: item => {
          return (
            <div>
              <a className="be-color" onClick={() => this.wrapChangeModalVisible(true, item)}>
                编辑
              </a>
              <Popconfirm
                placement="bottomRight"
                title={'确定删除吗'}
                onConfirm={() => this.deleteWhiteIp(item._id)}
                okText="确定"
                cancelText="取消"
              >
                <a style={{ marginLeft: 10, color: '#F04038' }}>删除</a>
              </Popconfirm>
            </div>
          );
        }
      }
    ];
    const pagination = {
      total: count,
      current: filter.page,
      pageSize: filter.pageSize,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showSizeChanger: true,
      showTotal: num => `共 ${num} 条`,
      size: 'small'
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, rows) => {
        const selectedRows = _.map(rows, '_id');
        this.setState({ selectedRows, selectedRowKeys });
      }
    };
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>
          禁扫目标管理
          <Tooltip
            className="info"
            placement="right"
            overlayClassName={`${prefixCls}-page-title-desc`}
            title="当禁扫目标开启后，加入了禁扫目标的 IP 将不会执行所下发的检测任务"
          >
            <Icon type="exclamation-circle" />
          </Tooltip>
        </div>
        <div className={`${prefixCls}-operate`}>
          <div>
            <Button type="primary" onClick={() => this.wrapChangeModalVisible(true, {})}>
              添加禁扫目标
            </Button>
            <Button
              className={`${prefixCls}-operate-btn`}
              onClick={() => this.batchDel('del')}
              disabled={selectedRows.length === 0}
            >
              批量删除
            </Button>
            <Button className={`${prefixCls}-operate-btn`} onClick={() => this.batchDel('drop')}>
              清空禁扫目标
            </Button>
            <WhiteListModal
              modalVisible={modalVisible}
              closeModal={() => this.wrapChangeModalVisible(false)}
              onClickSubmit={this.onClickSubmit}
              confirmLoading={confirmLoading}
              rowData={rowData}
            />
            <Modal
              maskClosable={false}
              className="tm-more-modal"
              visible={Boolean(modalType)}
              title={`${OP_TYPE[modalType] || ''}`}
              okText="确认"
              cancelText="取消"
              onCancel={() => this.setState({ modalType: '' })}
              onOk={this.onDelOrDrop}
              // confirmLoading={true}
            >
              确认{OP_TYPE[modalType] || ''}吗?
            </Modal>
          </div>
          <div>
            <Search
              value={filter.search}
              enterButton
              placeholder="请输入备注或IP"
              onChange={this.onSearchChange}
              onSearch={value => {
                let search = value.toString();
                filter.search = search;
                filter.page = 1;
                this.setState({ filter }, this.getWhiteList);
              }}
            />
          </div>
        </div>
        {total ? (
          <div>
            <div className={`${prefixCls}-header-count`}>共有 “{count}” 个禁扫目标组</div>
            <Table
              rowSelection={rowSelection}
              loading={loading}
              columns={columns}
              pagination={pagination}
              dataSource={data}
              onChange={this.onTableChange}
            />
          </div>
        ) : (
          <Empty
            image={EmptyDataImg}
            imageStyle={{
              margin: '120px 0 24px',
              height: 296
            }}
            description={
              <div>
                <span style={{ color: '#2A2B30' }}>您还未创建过禁扫目标</span>
                <p style={{ marginTop: 8, color: '#999EA8' }}>
                  当禁扫目标开启后，加入了禁扫目标的IP将不会执行所下发的检测任务，
                  <br />
                  您可以通过左上角按钮添加
                </p>
              </div>
            }
          />
        )}
      </div>
    );
  }
}

export default WhiteList;
